package org.zerhusen.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 有安全凭证，但是凭证未通行
 * */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

   @Override
   public void commence(HttpServletRequest request,
                        HttpServletResponse response,
                        AuthenticationException authException) throws IOException {
      // 当用户尝试访问安全的REST资源而不提供任何凭据时，我们应该只发送401未经授权的响应，
      // 因为没有 “登录页面” 重定向到这里你可以放置任何你想要的消息
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());

//      response.setContentType("application/json;charset=utf-8");
//      Map<String, Object> map = new HashMap<>(4);
//      // 这里写死只做测试  请以实际为主
//      map.put("code", HttpServletResponse.SC_BAD_GATEWAY);
//      map.put("message", "请登录！");
//      response.getWriter().println(JSON.toJSONString(map));
//      response.getWriter().flush();
   }
}
